package org.kth.dks;

import org.apache.log4j.Logger;

/**
 * <p>Title: DKSObject class </p>
 * <p>Description: A simple wrapper for a byte array</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: KTH-IMIT</p>
 * @author not attributable
 * @version 1.0
 */

public class DKSObject {
	private Logger log = Logger.getLogger(DKSObject.class);
	private DKSObjectTypes type;
  private byte [] data;
  /**
   * Makes a shallow copy of the byte stream, object type will be DKSObjectTypes.DEFAULT
   * @param newData byte[] arbitrary byte array
   */
  public DKSObject(byte[] newData) {
    data = newData;
    type=DKSObjectTypes.DEFAULT;
  }

  /**
   * Makes a shallow copy of the byte stream, object type will be type
   * @param type DKSObjectTypes type of the object
   * @param newData byte[] arbitrary byte array
   */
  public DKSObject(DKSObjectTypes type,  byte[] newData ) {
    data = newData;
    this.type=type;
  }

  /**
   * WARNING! This constructor should not be public
   * It is used internally to take a BASE64 representation of an byte array
   * @param base64 String representation of the byte array in BASE64 encoding
   */
  public DKSObject( String base64 ) {
    try {
      base64=base64.replace(' ','\n'); // ali: quick dirty hack ( O(n) slowdown in parsing ), need to fix this!
      byte[] decdata = new sun.misc.BASE64Decoder().decodeBuffer(base64);
      data = new byte[ decdata.length - 1 - decdata[0] ];
      System.arraycopy( decdata, 1+decdata[0], data, 0, decdata.length-1-decdata[0] );
      char[] decstr = new char[decdata[0]];
      for (int i=0; i<decstr.length; i++) {
        decstr[i] = (char) decdata[i+1];
      }
      type = DKSObjectTypes.valueOf( new String(decstr) );
    }
    catch (java.io.IOException ex)
    {
      data=new byte[]{0};
      log.error("Couldn't unmarshal base64 string (DKSObject)");
      ex.printStackTrace();
    }
  }

  /**
   * Each DKSObject has a DKSObjectType value associated with it to allow multiplexing without looking at the payload
   * @return DKSObjectTypes type of this DKSObject
   */
  public DKSObjectTypes getType() {
    return type;
  }

  /**
   * Returns the internal byte array that this wrapper class stores
   * @return byte[]
   */
  public byte[] getData() {
    return data;
  }

  /**
   * WARNING! This method should not be public
   * It returns a BASE64 encoded version of the internal byte array
   * @return String
   */
  public String toString() {
    char[] carr = type.getName().toCharArray();
    byte [] encdata = new byte[carr.length+1+data.length];
    for(int i=0; i<carr.length; i++) {
      encdata[i+1] = (byte)carr[i];
    }
    encdata[0] = (byte)carr.length;
    System.arraycopy(data, 0, encdata, carr.length+1, data.length);
    return new sun.misc.BASE64Encoder().encode(encdata);
  }
}
